<template>
    <s-layout v-if="showConfig.text" onShareAppMessage :tabbarshow="false" id="layout" navbar="normal">
      <view class="page-body">
        <view class="page-section page-section-gap">
          <map class="map" :latitude="mapConfig.latitude" :longitude="mapConfig.longitude" :markers="mapConfig.covers" :circles="mapConfig.circles"></map>
        </view>
        <view class="page-content">
          <view class="wrap">
            <view @click="clickLeworkClockin(showConfig.status)" v-if="showConfig.status == 4" class="legwork">
              <text class="text">{{
            showConfig.text }}</text><text class="text">{{ clockingTime }}</text>
            </view>
            <view  v-else-if="showConfig.status == 5" class="gary">
              <text class="text">{{
            showConfig.text }}</text>
            </view>
            <view v-else :class="showConfig.color == 1 ? 'schedule' : showConfig.color == 2 ? 'belate' : ''"
              @click="clickClockin(showConfig.status)"><text class="text">{{
            showConfig.text }}</text><text class="text">{{ clockingTime }}</text></view>
            <view class="index-address">
              <u-icon size="20" name="map-fill" color="#2979ff"></u-icon>
              <view class="address-name">{{ mapConfig.locationAddress }}</view>
              <u-icon size="20" name="reload" color="#2979ff" @click="refreshPosition"></u-icon>
            </view>
          </view>
  
  
          <!-- //打卡列表 -->
          <view class="clockstatus">
            <view class="item">
              <view class="each-item">上班<text class="texts">{{ nowDayClockData.beOnDutyTime }}</text></view>
              <view :class="!nowDayClockData.offDutyTime ? 'status' : 'blues'">{{ !nowDayClockData.beOnDutyTime ? '未打卡' :
            '已打卡' }}</view>
            </view>
            <view class="item">
              <view class="each-item">下班<text class="texts">{{ nowDayClockData.offDutyTime }}</text></view>
              <view :class="!nowDayClockData.offDutyTime ? 'status' : 'blues'">{{ !nowDayClockData.offDutyTime ? '未打卡' :
            '已打卡' }}</view>
            </view>
          </view>
          <!-- 弹窗 -->
          <index-modal @closepop="closepop" :show="popshows" :dataToinformaion="dataToinformaion"></index-modal>
          <!-- 外勤打卡弹窗 -->
          <u-popup :show="legworkPopShow" mode="bottom">
            <view class="legwork_pop">
              <view class="legwork_pop_form">
                <up-form :model="formData" ref="legworkPopFormRef" :rules="rules" labelPosition="top" labelWidth="120">
                  <up-form-item label="外勤备注" prop="notes" :required="true" label-height="90rpx">
                    <up-input v-model="formData.notes" placeholder="请输入"
                      :customStyle="{ border: '2rpx solid #ddd', background: '#F4F6FA', height: '100rpx' }" />
                  </up-form-item>
                  <up-form-item label="外勤拍照" prop="fileList1" :required="true">
                    <u-upload :fileList="formData.fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
                      :maxCount="1"></u-upload>
                  </up-form-item>
                </up-form>
                <button class="submit" @tap="fieldServiceSubmit(showConfig.status)">提交外勤打卡</button>
                <view class="remove" @tap="fieldServiceRemove">取消</view>
              </view>
            </view>
          </u-popup>
        </view>
      </view>
    </s-layout>
    <view v-else>
          <up-loading-page
              :loadingText="loadingPageData.loadingText"
              :image="loadingPageData.image"
                :iconSize="loadingPageData.iconSize"
              :loadingMode="loadingPageData.loadingMode"
              :bgColor="loadingPageData.bgColor"
              :loading="true"
              :color="loadingPageData.color"
              :loadingColor="loadingPageData.loadingColor"
          >
          </up-loading-page>
      </view>
  </template>
  <script setup>
  import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
  import { ref, computed, reactive, unref } from 'vue';
  import sheep from '@/sheep';
  import indexModal from './components/index-modal.vue';
  
  import {showAuthModal} from '@/sheep/hooks/useModal';
  import { getLocation,getRequest} from '@/utils/locationUtils';
  const userStore = sheep.$store('user');
  
  let systemClockConfig = reactive({}) //公司设置数据
  
  const loadingPageData = reactive({
                      // 自定义提示内容
                      loadingText: '加载中',
                      // 自定义图片
                      image: sheep.$url.cdn(sheep.$store('app').info.logo),
                      // 自定义加载动画模式
                      loadingMode: 'circle',
                      // 自定义背景色
                      bgColor: '#ffffff',
            iconSize: '38'
                  })
  
  let showConfig = reactive(
  {
    status: '',//状态:4=外勤，5禁止打卡
    color: '',
    text: '',
  }
  )//打卡返回数据
  const clockingTime = ref('18:10:20')//即时时间
  const currentTime  = ref()//当前时间年月日时分秒
  const mapConfig = reactive({
    latitude: '',
    longitude: '',
    covers: [],
    circles: [],
    locationAddress: '',
    distance: '',
  })
  // 外勤响应式表单数据  
  const legworkPopFormRef = ref(null)
  const formData = ref({
    notes: '',
    fileList1: [],
    uploadimg: ''
  });
  // 外勤校验规则  
  const rules = {
    'notes': [
      {
        required: true,
        message: '请输入备注',
      },
    ],
    'fileList1': [
      {
        required: true,
        message: '请上传照片',
      },
    ],
  };
  
  let nowDayClockData = ref([])//当天考勤数组
  const isLogin =  sheep.$store('user').isLogin;
  onLoad((options) => {
    getConfig()
    getLocationAddress()
  })
  onShow(() => {
    updateCurrentTime()
  })
  
    //请求打卡设置数据
  async function getConfig() {
  //  uni.showLoading({
  //   title: '加载中'
  // });
  const res = await sheep.$api.attendance_record.getConfig();
  if(res.code == 1) {
    systemClockConfig = res.data
    // uni.hideLoading()
    } else {
      showConfig.text = res.msg
      showConfig.status = '5',
      sheep.$helper.toast(res.msg)
    }
  }
  //刷新当前位置
  const isClicked = ref(false)
  const refreshPosition = () => {
    if (isClicked.value) {
      sheep.$helper.toast('操作过于频繁，请稍后再试！')
      return;
    }
    isClicked.value = true;
    getLocationAddress();
    setTimeout(() => {
      isClicked.value = false;
    },5000)// 禁止5秒内的重复点击
   
  }
  //更新时间
  function updateCurrentTime() {
  const date = new Date();
  let hours = date.getHours().toString().padStart(2, '0');
  let minutes = date.getMinutes().toString().padStart(2, '0');
  let seconds = date.getSeconds().toString().padStart(2, '0');
  clockingTime.value = `${hours}:${minutes}:${seconds}`; //当前时间
  currentTime.value = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/,
    ''); //当前年月日时分秒
    updateClockStatus()
  if (!clocking_interval.value) {
    clocking_interval.value = setInterval(() => {
      updateCurrentTime(); // 每隔1000ms（1s）更新一次时间
    }, 1000);
  }
  }
  
  //授权获取地址
  function getLocationAddress() {
    getLocation().then((result) => {  
      mapConfig.latitude = result.latitude;
      mapConfig.longitude = result.longitude;
      let location = result.latitude + ',' + result.longitude;
      let obj = {}
      obj.latitude = result.latitude;
      obj.longitude = result.longitude;
      obj.fillColor = '#4C9BD930',
      obj.radius = 100
      obj.strokeWidth = 2,
  
      obj.color = '#ffffff',
      obj.id = 1,
      obj.width = 23,
      obj.height = 36,
      obj.iconPath = sheep.$url.cdn('/uploads/uniapp_image/staff/dingwei.png')
      mapConfig.circles = [];
      mapConfig.covers = [];
      mapConfig.circles.push(obj)
      mapConfig.covers.push(obj)
  
      getRequest(location).then((ret) =>{
        mapConfig.locationAddress = ret.data.result.address;
      }).catch((error) => {  
        sheep.$helper.toast('无法获取位置信息！无法使用位置功能')
          // 如果 Promise 拒绝，则捕获错误  
      }); 
      getTodayAttendancw()
  
      }).catch((error) => {  
        sheep.$helper.toast('您已经拒绝授权，打卡可能受限制！')
      }); 
  
  
  }
  
  
  //当天考勤数据
  async function getTodayAttendancw() {
  // 请求考勤数据，地图回显 获取定位信息
  const res = await sheep.$api.attendance_record.getTodayAttendancw({})
  if (res.code == 1) {
    //判断打卡信息
    // 示例：计算两个经纬度的距离
    mapConfig.distance = getDistance(
        mapConfig.latitude + 0.024,
        mapConfig.longitude + 0.002482,
      systemClockConfig.lat,
      systemClockConfig.lon,
    );
    nowDayClockData.value = res.data;
    // 
    mapConfig.distance = Math.abs(mapConfig.distance - 2000)
    updateClockStatus()
    setTimeout(function () {
      // uni.hideLoading();
    }, 2000);
  
  }
  }
  //打卡封装
  const updateClockStatus =()=>{
    const lon_lat_range = parseInt(systemClockConfig.lon_lat_range)
  if(mapConfig.distance > lon_lat_range) {
    // 外勤
    showConfig.text = '外勤打卡'
    showConfig.color = '3',
    showConfig.status = '4'
  } else {
    // 正常
    if(clockingTime.value <= systemClockConfig.demarcation_time) {
        showConfig.text = '上班打卡'
        showConfig.color = '1'
        if(clockingTime.value > systemClockConfig.start_time) {
            showConfig.text = '迟到打卡'
            showConfig.color = '2'
        }
    } else if (clockingTime.value > systemClockConfig.demarcation_time) {
        showConfig.text = '下班打卡'
        showConfig.color = '1'
        if(clockingTime.value < systemClockConfig.end_time) {
            showConfig.text = '早退打卡'
            showConfig.color = '2'
        }
    }
  }
  nowDayClockData.value.forEach((i) => {
    
  if (i.type == 1) {
    nowDayClockData.value.beOnDutyTime = i.clocking_time.split(' ').slice(1).join(' ');
    if(clockingTime.value <= systemClockConfig.demarcation_time) {
      showConfig.text = '更新打卡'
      showConfig.color = '1'
    }
  }
  if (i.type == 2) {
    nowDayClockData.value.offDutyTime = i.clocking_time.split(' ').slice(1).join(' ');
    if(clockingTime.value >= systemClockConfig.demarcation_time) {
      showConfig.text = '更新打卡'
      showConfig.color = '1'
    }
  }
  })
  }
  // 点击正常打卡
  const clickClockin = (event) => {
    postClockin(event)
  
  }
  //外勤打卡弹窗值
  const legworkPopShow = ref(false);
  //外勤打卡
  const clickLeworkClockin = (event) => {
    if (!mapConfig.longitude && !mapConfig.latitude && !mapConfig.locationAddress) {
      sheep.$helper.toast('请开启手机定位后进行外勤打卡！')
    } else {
      legworkPopShow.value = true
    }
  }
  //取消外勤打卡彈窗
  const fieldServiceRemove = () => {
    legworkPopShow.value = false
    legworkPopFormRef.value.clearValidate();
    legworkPopFormRef.value.resetFields();
  }
  
  // 删除图片
  const deletePic = (event) => {
    formData.value.fileList1.splice(event.index, 1);
  };
  
  // 新增图片
  const afterRead = async (event) => {
    let lists = [].concat(event.file);
    let fileListLen = formData.value.fileList1.length;
    lists.map((item) => {
      formData.value.fileList1.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      });
    });
    for (let i = 0; i < lists.length; i++) {
      const result = await uploadFilePromise(lists[i].url);
      let item = formData.value.fileList1[fileListLen];
      formData.value.fileList1.splice(fileListLen, 1, {
        ...item,
        status: 'success',
        message: '',
        url: result,
      });
      fileListLen++;
    }
  };
  const postData = ref([])
  async function uploadFilePromise(tempUrl) {
    let { url } = await sheep.$api.app.upload(tempUrl, 'ugc');
    postData.value = url
    return postData;
  };
  
  // 提交方法  
  const fieldServiceSubmit = (event) => {
    legworkPopFormRef.value.validate().then(valid => {  
      if (valid) {  
          postClockin(event)
          legworkPopShow.value = false
          legworkPopFormRef.value.clearValidate();
          legworkPopFormRef.value.resetFields();
      } 
    }).catch(() => {  
      // 处理验证错误 
      sheep.$helper.toast(res.msg)
    });  
  
  
  
  }
  
  // 打卡方法封装
  function postClockin(event) {
    const  remark = formData.value.notes
    if (isLogin == false) {
      showAuthModal()
    } else {
      // #ifdef MP-WEIXIN
      uni.authorize({
        scope: 'scope.userLocation',
        success() { //1.1 允许授权
          dataToinformaion.value.title = showConfig.text
          formData.value.uploadimg = postData
        sheep.$api.attendance_record.postClockin({
            lon: mapConfig.longitude,
            lat: mapConfig.latitude,
            address: mapConfig.locationAddress,
            is_makeup_card: 0,//正常1补卡
            is_legwork: event == 4 ? 1 : 0,
            clocking_time: event == 4 ? clockingTime.value : '',
            image: event == 4 ? formData.value.uploadimg : '',
            remark:remark,
          }).then((res) => {
                // uni.hideLoading()
            if(res.code == 1){
              dataToinformaion.value.time = clockingTime.value
              setTimeout(()=>{
                  popshows.value = true
              },500)
              getTodayAttendancw()
            }else{
              sheep.$helper.toast(res.meg)
            }
          }).catch((err) => {
            sheep.$helper.toast(err.msg)
            
          })
        },
        fail() {
          uni.showModal({
            content: '检测到您没打开获取信息功能权限，是否去设置打开？',
            confirmText: "确认",
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (res) => {
                    getLocationAddress()
                  }
                })
              } else {
                return false;
              }
            }
          })
          return false;
        }
      })
  
      // #endif
    }
  }
  //打卡弹窗
  const popshows = ref(false)
  const dataToinformaion = ref({
    title: '',
    time: '',
    subtitle: '坚持不懈，成功将会来临！',
    imageSrc: '/uploads/uniapp_image/staff/daka01.png',
    dialogButton: '我知道了',
  })
  //打卡弹窗关闭
  function closepop(e) {
    popshows.value = e
  }
  //处理距离
  function getDistance(lat1, lon1, lat2, lon2) {
    const earthRadius = 6371000; // 地球半径，单位：米
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLon = (lon2 - lon1) * Math.PI / 180;
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI /
      180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = earthRadius * c;
    return distance;
    // return `${distance}`;
  }
  
  //离开界面删除计时器
  const clocking_interval = ref(null);
  onHide(() => {
  if (clocking_interval.value) {
    clearInterval(clocking_interval.value);
    clocking_interval.value = null
  }
  })
  
    
  
  </script>
  
  
  <style lang="scss" scoped>
  @import './components/index.scss';
  
  .map {
  width: 100%;
  height: 64vh;
  }
  </style>